﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace TipokHostManagerTest
{
    public class TestWorker
    {
        public TestWorker()
        { }

        private bool _running = false;

        public bool IsRunning
        {
            get { return _running; }
        }

        public void Start()
        {
            Demo();
            _running = true;
        }

        public void Stop()
        {
            _running = false;
        }

        public void Demo()
        {
            ServiceController[] services = ServiceController.GetServices(".");
            foreach (ServiceController service in services)
            {
                Console.WriteLine(string.Format("{0} [ {1} ] {0}",
                    service.ServiceName, service.Status.ToString()));
            }
            ServiceController serviceItem = new ServiceController("TipokService", ".");
            while (serviceItem.Status != ServiceControllerStatus.Stopped)
            {
                serviceItem.Stop();
                serviceItem.WaitForStatus(ServiceControllerStatus.Stopped);
            }
            serviceItem.Start();
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.WorkingDirectory = @"E:\work\Hosting\bin\Debug";
            //p.StartInfo.CreateNoWindow = true;
            p.Start();
            System.IO.StreamReader strm = System.IO.File.OpenText(@"E:\work\Hosting\bin\Debug\uninstall.bat");
            //p.ErrorDataReceived += new DataReceivedEventHandler(p_DateErrReceiver);
            //p.BeginErrorReadLine();
            System.IO.StreamWriter sIn = p.StandardInput;
            while (strm.Peek() != -1)
            {
                sIn.WriteLine(strm.ReadLine());  //写入
            }
            strm.Close();
            //sIn.WriteLine("DEL " + strFilePath);//执行完删除bat
            sIn.WriteLine("EXIT");
            p.Close();
            sIn.Close();
            Console.Read();
            //CACLS Comm.dll /G Everyone:F
            TimeSpan t = TimeSpan.FromSeconds(10);
            //serviceItem.WaitForStatus(ServiceControllerStatus.Running, t);
        }
    }
}
